package com.demo.lengthFieldBasedFrameDecoder.demo1;

import com.alibaba.fastjson.JSON;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class NettyClient {

    public static void main(String[] args) {
        NettyClient client = new NettyClient();
        client.start("127.0.0.1", 8888);
    }

    public void start(String host, int port) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            //添加编码器
                            //参数，固定的header是多少，我屏蔽了，通过自己去写字节进去了
                            //pipeline.addLast(new LengthFieldPrepender(4));

                            //添加客户端channel对应的handler
                            pipeline.addLast(new ClientInboundHandler());
                        }
                    });
            //连接远程启动
            ChannelFuture future = bootstrap.connect(host, port).sync();
            //监听通道关闭
            Channel channel = future.channel();

            channel.closeFuture().sync();

        } catch (Exception e) {
            log.error("netty client error ,msg={}", e.getMessage());
        } finally {
            //优雅关闭
            group.shutdownGracefully();
        }
    }


    @Slf4j
   static public class ClientInboundHandler extends ChannelInboundHandlerAdapter {


        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            for (int i = 1; i <= 10; i++) {
                UserInfo userInfo = new UserInfo(i, "rosh" + i);
                byte[] bytes = JSON.toJSONString(userInfo).getBytes(StandardCharsets.UTF_8);
                //根据字节长度来做编码呢
                ByteBuf byteBuf = ctx.alloc().buffer();
                byteBuf.writeInt(bytes.length);//int 占用4个字节，把长度写进去呢。
                byteBuf.writeBytes(bytes);
                ctx.channel().writeAndFlush(byteBuf);
            }
            super.channelActive(ctx);
        }
    }

}
